package com.example.group.network.express_plus_app.data;

import android.app.Application;
import android.content.Context;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.group.network.express_plus_app.R;
import com.example.group.network.express_plus_app.bean.Token;
import com.example.group.network.express_plus_app.bean.User;
import com.example.group.network.express_plus_app.data.model.LoggedInUser;
import com.example.group.network.express_plus_app.http.GsonRequest;
import com.example.group.network.express_plus_app.http.MySingleton;

import java.util.HashMap;
import java.util.Map;


/**
 * Class that handles authentication w/ login credentials and retrieves user information.
 */
public class LoginDataSource {
    String server_ip;

    RequestQueue queue;
    String request_token_url;
    String request_user_url;
    private Token token;
    public void login(String username, String password, Application applicationContext) {

        server_ip=applicationContext.getString(R.string.server_ip);
        request_token_url=server_ip+"express-auth2/oauth/token?";
        request_user_url=server_ip+"express-user/user-controller/find-user-info-by-phone?";
        //初始化queue
        queue= MySingleton.getInstance(applicationContext).
                getRequestQueue();

        requestToken(username, password);

    }

    public void logout() {
        // TODO: revoke authentication
    }


    public void requestToken(String phone, String password )  {
        Log.i("token","开始请求token");
        GsonRequest<Token> tokenGsonRequest=new GsonRequest<Token>(request_token_url, Request.Method.POST, Token.class, null, new Response.Listener<Token>() {
            @Override
            public void onResponse(Token response) {
                Log.i("token", response.getAccess_token());
                //调用请求用户信息的方法
                requestUser(response.getAccess_token(),phone);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("LoginDataSource", error.toString());
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> parms=new HashMap<>();
                parms.put("grant_type","password");
                parms.put("client_id","c1");
                parms.put("client_secret","123456");
                parms.put("username",phone);
                parms.put("password",password);
                return parms;
            }
        };
        tokenGsonRequest.setRetryPolicy(new DefaultRetryPolicy(6000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(tokenGsonRequest);

    }

    //请求用户信息
    public void requestUser(String token,String phone){
        Map<String,String> head=new HashMap<>();
        head.put("Authorization","Bearer "+token);
        GsonRequest<User> userGsonRequest=new GsonRequest<User>(request_user_url, Request.Method.POST, User.class, head, new Response.Listener<User>() {
            @Override
            public void onResponse(User response) {
                //调用请求用户信息的方法
                //将token保存到共享参数
                Log.i("user",response.toString());
                //信息回调
                LoggedInUser loggedInUser=new LoggedInUser(response.getUserPhone(),response.getUserNetName(),
                        token,response.getUserFace(),response.getUserDeliveryAddress().getDeliveryAddress());
                Result.Success<LoggedInUser> loggedInUserSuccess = new Result.Success<>(loggedInUser);
                responseListener.setResultSuccess(loggedInUserSuccess);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("LoginDataSource", "用户信息请求错误"+error.toString());
                Result.Error error1 = new Result.Error(error);
                responseListener.setResultError(error1);
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> parms=new HashMap<>();
                parms.put("userPhone",phone);
                return parms;
            }
        };
        userGsonRequest.setRetryPolicy(new DefaultRetryPolicy(6000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(userGsonRequest);
    }




    //回调使用
    private ResponseListener responseListener; //定义一个用户信息监听器
    public void setResponseListener(ResponseListener listener){
        responseListener=listener;
    }
    public interface ResponseListener{
        void setResultSuccess(Result.Success<LoggedInUser> result);
        void setResultError(Result.Error error);
    }



}